using System;

using FirebirdSql.Data.FirebirdClient;
using FirebirdSql.Data.Isql;

namespace Server.FunctionalTests.Dal.Helpers
{
  public class FbDatabase : IDisposable
  {
    private readonly string _connectionString;

    #region .ctors
    public FbDatabase( string createScriptFilePath, string databaseFilePath, bool embeded )
    {
      _connectionString = DeployDatabase( createScriptFilePath, databaseFilePath, embeded );
    }
    #endregion

    public static string DeployDatabase( string createScriptFilePath, string databaseFilePath, bool embeded )
    {
      var connectionStringBuilder = new FbConnectionStringBuilder {Charset = "UTF8", Database = databaseFilePath};

      if( embeded )
      {
        connectionStringBuilder.ServerType = FbServerType.Embedded;
      }
      else
      {
        connectionStringBuilder.DataSource  = "localhost";
        connectionStringBuilder.UserID      = "SYSDBA";
        connectionStringBuilder.Password    = "masterkey";
      }

      var connectionString = connectionStringBuilder.ToString();
      FbConnection.CreateDatabase( connectionString, true );

      var script = new FbScript( createScriptFilePath );
      script.Parse();

      using( var connection = new FbConnection( connectionStringBuilder.ToString() ) )
      {
        var batchExecution = new FbBatchExecution( connection );
        foreach( var command in script.Results )
          batchExecution.SqlStatements.Add( command );

        batchExecution.Execute( true );
      }
      return connectionString;
    }

    public string ConnectionString
    {
      get { return _connectionString; }
    }

    public void Dispose()
    {
      FbConnection.ClearAllPools();
      FbConnection.DropDatabase( _connectionString );
    }
  }
}